package service

import (
	"encoding/json"
	"gitee.com/ai-love-save/ai-love-save-back/app/utils"
	"github.com/google/wire"
	"go.uber.org/zap"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
)

var TokenSet = wire.NewSet(wire.Struct(new(Tokendepend), "*"))

type Tokendepend struct {
	Logger *zap.Logger
}

type ResData struct {
	AccessToken string `json:"accesstoken"`
	ExpiresIn   int    `json:"expireTime"`
}

type ResTokenBody struct {
	Msg  string  `json:"msg"`
	Code string  `json:"code"`
	Data ResData `json:"data"`
}

func PostForms(appKey, appSecret string) (*ResTokenBody, error) {
	targeturl := "https://open.ys7.com/api/lapp/token/get"
	forms, err := http.PostForm(targeturl, url.Values{"appKey": {appKey}, "appSecret": {appSecret}})
	if err != nil {
		return nil, utils.ErrUrlGetFailed
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(forms.Body)

	body, err := ioutil.ReadAll(forms.Body)
	if err != nil {
		return nil, utils.ErrUrlGetFailed
	}
	var resBody ResTokenBody
	if err = json.Unmarshal(body, &resBody); err != nil {
		//fmt.Printf("Unmarshal err, %v\n", err)
		return nil, utils.ErrUrlGetFailed
	}

	return &resBody, nil
}

func (t *Tokendepend) RegetToken() (error, string) {
	content, err := PostForms("bf3a77de21eb45ba80eec0dce4da453e", "6c26f0ce3bdd85e6c0a2e7cbc07dd3a3")
	if err != nil {
		t.Logger.Warn("服务处理失败", zap.Error(err))
		return utils.ErrTokenMismatch, ""
	}
	//fmt.Println(content.Data.AccessToken)
	return nil, content.Data.AccessToken
}
